package com.acsior.hibernate.test;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import junit.framework.TestCase;

import com.acsior.dac.impl.hibernate.HibernateConfigurationFactory;

/**
 * Тест на инициализацията на фабриката за Hibernate. Може да се наследи от
 * други тест класове, на които им трябва сесия към базата посредством
 * Hibernate.
 * 
 * @author Г. Белев 10.08.2011
 */
public class HibernateTestModule extends TestCase {

	/** Флаг, показващ дали е инициализацията е успешна. */
	private static boolean inited;

	/** за базата данни */
	private TestDAO dao;

	private long time;

	private String workspace;

	/**  */
	public HibernateTestModule() {
		this.dao = new TestDAO();
	}

	/** За да се билдне конфигурацията */
	public void testConfiguration() {
		System.out.println("Configuration ОК!");
	}

	/**
	 * Добавя подаден jar към клас пътя
	 * 
	 * @param s
	 *            пълен път до jar-а
	 * @throws MalformedURLException
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 */
	@SuppressWarnings("deprecation")
	protected void addPath(String s) throws MalformedURLException, SecurityException,
			NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
			InvocationTargetException {
		File f = new File(s);
		URL url = f.toURL();

		URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

		Class<URLClassLoader> urlClass = URLClassLoader.class;
		Method method = urlClass.getDeclaredMethod("addURL", new Class[] { URL.class });
		method.setAccessible(true);

		method.invoke(urlClassLoader, new Object[] { url });
	}

	/** @return the dao */
	protected TestDAO getDao() {
		return this.dao;
	}

	/** @return the time */
	protected long getTime() {
		return this.time;
	}

	/** @return the workspace */
	protected String getWorkspace() {
		return this.workspace;
	}

	/** @see TestCase#setUp() */
	@Override
	protected void setUp() throws Exception {
		super.setUp();
		this.time = new Date().getTime();
		try {
			if (inited) {
				return;
			}
			String userDir = (String) System.getProperties().get("user.dir");
			this.workspace = userDir.substring(0, userDir.lastIndexOf("\\"));

			addPath(getWorkspace() + "/BGPOSTS/lib/asm-attrs.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/asm.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/cglib-2.1.3.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/commons-collections-2.1.1.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/dom4j-1.6.1.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/ejb3-persistence.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/hibernate-annotations.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/hibernate-commons-annotations.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/hibernate-entitymanager.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/hibernate-validator.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/javassist.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/jta.jar");
			addPath(getWorkspace() + "/BGPOSTS/lib/sqljdbc.jar");

			HibernateConfigurationFactory factory = new HibernateConfigurationFactory();
			Map<String, String> params = new HashMap<String, String>();

			//params.put("hibernate.show_sql", "true");
			params.put("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
			params.put("hibernate.connection.isolation", "2");
			params.put("hibernate.transaction.factory_class",
					"org.hibernate.transaction.JDBCTransactionFactory");
			params.put("hibernate.current_session_context_class", "thread");
			params.put("hibernate.connection.url",
					"jdbc:sqlserver://172.16.134.237:1435;databaseName=BGPOSTSDB");
			params.put("hibernate.connection.username", "sa");
			params.put("hibernate.connection.password", "Pa550rdi23");
			params.put("hibernate.connection.driver_class",
					"com.microsoft.sqlserver.jdbc.SQLServerDriver");

			File configFile = new File(getWorkspace()
					+ "/HibernateLayer/test/com/acsior/hibernate/test/"
					+ "testHibernateClasses.properties");

			factory.initializeComponent(null, params, configFile);

			inited = true;

		} catch (Exception e) {
			e.printStackTrace();

			System.exit(0);
		}

	}
}
